// recorderMethods.js

import Recorder from 'recorder-core'
import 'recorder-core/src/engine/wav'
import 'recorder-core/src/extensions/waveview'

// ✅ 直接引入 Vuex store
import store from '@/store'

const recorderMethods = {
  rec: null,
  wave: null,
  sampleBuf: [],
  isRecording: '1',

  /** 打开设备 */
  open(success) {
    this.rec = new Recorder({
      type: 'wav',
      sampleRate: 16000,
      bitRate: 16,
      onProcess: (buffer, powerLevel, bufferDuration, bufferSampleRate) => {
        recorderMethods.recProcess(
          buffer,
          powerLevel,
          bufferDuration,
          bufferSampleRate
        )
      }
    })

    this.rec.open(
      () => success && success(),
      (error) => {
        alert(error)
        // console.log('openError:', error) // 打印错误信息
        // this.$notify({
        //   title: '错误',
        //   message: error || '设备打开失败，请检查设备连接或权限设置。'
        // })
      }
    )
  },

  recStart() {
    this.rec.start()
    console.log('开始录音了')
  },

  recStop() {
    // console.log('执行了结束录音', this.sampleBuf)

    const chunk_size = [5, 10, 5]
    const request = {
      chunk_size,
      wav_name: 'h5',
      is_speaking: false,
      chunk_interval: 10,
      mode: '2pass-offline'
    }

    if (this.sampleBuf.length > 0) {
      const int16 = new Int16Array(this.sampleBuf)
      store.dispatch('wscont/wsSend', int16)
      console.log('sampleBuf.length: ' + this.sampleBuf.length)
      this.sampleBuf = []
    }

    store.dispatch('wscont/wsSend', JSON.stringify(request))
    this.rec.stop()
    this.isRecording = '2'
  },

  recOpen() {
    this.open(() => {
      this.recStart()
      this.isRecording = '1'
    })
  },

  recProcess(buffer, powerLevel, bufferDuration, bufferSampleRate) {
    if (this.isRecording === '1') {
      const data_48k = buffer[buffer.length - 1]
      const array_48k = [data_48k]
      const data_16k = Recorder.SampleData(
        array_48k,
        bufferSampleRate,
        16000
      ).data

      this.sampleBuf.push(...data_16k)

      const chunk_size = 960
      while (this.sampleBuf.length >= chunk_size) {
        const sendBuf = new Int16Array(this.sampleBuf.slice(0, chunk_size))
        this.sampleBuf = this.sampleBuf.slice(chunk_size)
        store.dispatch('wscont/wsSend', sendBuf)
      }
    }

    if (this.wave) {
      this.wave.input(buffer[buffer.length - 1], powerLevel, bufferSampleRate)
    }
  },

  recPause() {
    this.isRecording = '3'
    this.rec.pause()
  },

  recResume() {
    console.log('恢复录音')
    this.isRecording = '1'
    this.rec.resume()
  }
}

export default recorderMethods
